﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wabo.Dal;
using Wabo.Web.Areas.Manager.Core;
using Wabo.Web.Areas.Manager.Core.Attributes;
using Wabo.Web.Resources;

namespace Wabo.Web.Areas.Manager.Controllers
{
    [UserAuthorized]
    public class SystemSettingsController : WaboController
    {
        private IEnumerable<SelectListItem> GetThemes()
        {
            var themes = new List<SelectListItem>();
            foreach (var dir in Directory.GetDirectories(Server.MapPath(WaboViewEngine.ThemesBasePath)))
            {
                var folderName = new DirectoryInfo(dir).Name;
                themes.Add(new SelectListItem { Text = folderName, Value = folderName });
            }
            return themes;
        }
            
        [ModuleListPermission]
        [ModuleReadPermission]        
        public ActionResult Index()
        {
            // Search directories for themes            
            ViewBag.Themes = GetThemes();
            SystemSettings model = SystemSettingsContext.Settings;
            return View(model);
        }

        [HttpPost]
        [ModuleListPermission]
        [ModuleReadPermission]
        [ModuleWritePermission]
        public ActionResult Index( SystemSettings model)
        {
            string oldTheme = SystemSettingsContext.Theme;

            if (ModelState.IsValid)
            {
                SystemSettingsContext.Save(model);
                AddInfoMessage( Messages.DISP_SystemSettingsUpdated );
            }
            // Theme changed?
            if (!model.theme.Equals(oldTheme, StringComparison.OrdinalIgnoreCase))
            {                
                ViewEngines.Engines.Remove(ViewEngines.Engines.OfType<WaboViewEngine>().First());
                ViewEngines.Engines.Add(new WaboViewEngine(model.theme));
            }
            ViewBag.Themes = GetThemes();
            return View(model);
        }

    }
}
